<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区域 -->
    <el-card>
      <!-- 添加权限按钮 -->
      <!-- 角色列表表格 -->
      <el-row>
        <el-col>
          <el-button type="primary" plain @click="addRolesDialog = true">添加角色</el-button>
        </el-col>
      </el-row>
      <el-table :data="roleList" style="width: 100%" border stripe>
        <!-- 展开列 -->
        <el-table-column align="center" type="expand">
          <template slot-scope="scope">
            <!-- 权限渲染 -->
            <el-row
              :class="['bdborder', 'vcenter', index1 === 0 ? 'btborder' : '']"
              v-for="(item1, index1) in scope.row.children"
              :key="item1.id"
            >
              <!-- 渲染 1 级权限 -->
              <el-col :span="5">
                <el-tag
                  type="success"
                  closable
                  @close="removeRightById(scope.row,item1.id)"
                >{{ item1.authName }}</el-tag>
                <i class="el-icon-caret-right"></i>
              </el-col>
              <!-- 渲染 2 级以及 3 级权限 -->
              <el-col :span="19">
                <el-row
                  :class="[ index2 === 0 ? '' : 'btborder', 'vcenter']"
                  v-for="(item2, index2) in item1.children"
                  :key="item2.id"
                >
                  <!-- 渲染 2 级权限 -->
                  <el-col :span="6">
                    <el-tag
                      type="warning"
                      closable
                      @close="removeRightById(scope.row,item2.id)"
                    >{{ item2.authName }}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 渲染 3 级权限 -->
                  <el-col :span="18">
                    <el-tag
                      type="danger"
                      v-for="item3 in item2.children"
                      :key="item3.id"
                      closable
                      @close="removeRightById(scope.row,item3.id)"
                    >{{ item3.authName }}</el-tag>
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <!-- 索引列 -->
        <el-table-column align="center" type="index" label="#"></el-table-column>
        <el-table-column align="center" prop="roleName" label="角色管理"></el-table-column>
        <el-table-column align="center" prop="roleDesc" label="角色描述"></el-table-column>
        <el-table-column align="center" label="操作">
          <template slot-scope="scope">
            <el-button
              plain
              size="mini"
              type="primary"
              icon="el-icon-edit"
              @click="editRolesHandle(scope.row.id)"
            >编辑</el-button>
            <el-button
              plain
              size="mini"
              type="danger"
              icon="el-icon-delete"
              @click="removeRolesById(scope.row.id)"
            >删除</el-button>
            <el-button
              plain
              size="mini"
              type="warning"
              icon="el-icon-setting"
              @click="setRoles(scope.row)"
            >分配权限</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分配权限弹框 -->
    <el-dialog
      title="分配权限"
      :visible.sync="settingRolesDialog"
      width="50%"
      @close="settingRolesDialogClosed"
    >
      <!-- 树形控件区域 -->
      <!-- data 展示的数据 -->
      <!-- props 决定以哪种方式展示 tree 组件，如何定义父子关系 -->

      <!-- node-key：当我们选中某一权限时，我们不希望获取到的是文本，我们希望获取到的是能够代表当前权限的唯一值 -->
      <!-- default-expand-all 默认展示树形组件 -->
      <el-tree
        :data="rightsList"
        :props="treeProps"
        ref="treeRef"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="rightsKeysArr"
      ></el-tree>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="settingRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色弹框 -->
    <el-dialog
      title="添加角色"
      :visible.sync="addRolesDialog"
      width="50%"
      @close="addRolesDialogClosed"
    >
      <!-- 表单验证区域 -->
      <el-form
        :model="addRolesForm"
        :rules="addRolesFormRules"
        ref="addRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="addRoles">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑角色弹框 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="editRolesDialog"
      width="50%"
      @close="editRolesDialogClosed"
    >
      <!-- 表单验证区域 -->
      <el-form
        :model="editRolesForm"
        :rules="editRolesFormRules"
        ref="editRolesFormRef"
        label-width="100px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRolesForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRolesForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮区域 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editRolesDialog = false">取 消</el-button>
        <el-button type="primary" @click="editRoles">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: 'Roles',
  data() {
    return {
      // 角色列表数据
      roleList: [],
      // 控制分配权限弹框的显示与隐藏
      settingRolesDialog: false,
      // 所有权限的数据
      rightsList: [],
      treeProps: {
        children: 'children',
        label: 'authName'
      },
      // 已经选中的权限的id值数组
      rightsKeysArr: [],
      // 当前即将分配权限的角色id
      roleId: '',
      // 控制添加权限弹框的显示与隐藏
      addRolesDialog: false,
      // 添加角色数据对象
      addRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 添加角色表单验证规则对象
      addRolesFormRules: {
        // 角色名称验证规则
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        // 角色描述验证规则
        roleDesc: [{ min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }]
      },
      // 控制编辑权限弹框的显示与隐藏
      editRolesDialog: false,
      // 编辑角色数据对象
      editRolesForm: {
        roleName: '',
        roleDesc: ''
      },
      // 编辑角色表单验证规则对象
      editRolesFormRules: {
        // 角色名称验证规则
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
        ],
        // 角色描述验证规则
        roleDesc: [{ min: 0, max: 20, message: '长度在 0 到 20 个字符', trigger: 'blur' }]
      }
    }
  },
  created() {
    // 调用获取角色列表的方法
    this.getRoleList()
  },
  methods: {
    // 获取角色列表
    async getRoleList() {
      const { data: res } = await this.$http.get('/roles')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.roleList = res.data
    },

    // 移除权限
    async removeRightById(role, rightId) {
      const confirmRight = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)
      if (confirmRight !== 'confirm') return this.$message.error('取消了删除')
      // 发送移除权限的网络请求
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      role.children = res.data
    },

    // 分配权限
    async setRoles(roles) {
      this.roleId = roles.id
      const { data: res } = await this.$http.get('/rights/tree')
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.rightsList = res.data
      this.getLeayKey(roles, this.rightsKeysArr)
      this.settingRolesDialog = true
    },

    // 通过递归的形式，获取角色下所有三级权限的id，并保存到 rightsKeysArr 数组中
    // node 指需要递归的数据，此处指 scope.row
    // arr 指将获取到的 id 保存到哪里，此处指 rightsKeysArr
    getLeayKey(node, arr) {
      // 如果是三级节点，返回处理好的存放 id 的数组即可
      if (!node.children) {
        return arr.push(node.id)
      }
      // 如果不是三级节点，使用遍历的方式继续对内层的数据调用递归查询是否还存在 children 属性
      node.children.forEach(item => this.getLeayKey(item, arr))
    },

    // 监听分配权限弹框的关闭事件
    settingRolesDialogClosed() {
      this.rightsKeysArr = []
    },

    // 点击为角色分配权限
    async allotRights() {
      // 1. 获取半选和全选的id
      // 获取到引用对象，调用 element 提供的方法，获取到id
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]

      // 将参数处理成后台需要使用的字符型
      const idStr = keys.join(',')

      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
      this.settingRolesDialog = false
    },
    // 关闭添加角色弹框，整个表单进行重置
    addRolesDialogClosed() {
      this.$refs.addRolesFormRef.resetFields()
    },

    // 添加角色
    async addRoles() {
      this.$refs.addRolesFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.post('/roles', this.addRolesForm)
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg)
        this.$message.success(res.meta.msg)
        this.addRolesDialog = false
        this.getRoleList()
      })
    },

    // 点击编辑按钮，根据 ID 查询角色
    async editRolesHandle(id) {
      const { data: res } = await this.$http.get(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.editRolesForm = res.data
      this.editRolesDialog = true
    },

    // 关闭编辑角色弹框，整个表单进行重置
    editRolesDialogClosed() {
      this.$refs.editRolesFormRef.resetFields()
    },

    // 编辑角色
    editRoles() {
      this.$refs.editRolesFormRef.validate(async valid => {
        if (!valid) return

        const { data: res } = await this.$http.put(`/roles/${this.editRolesForm.roleId}`, {
          roleName: this.editRolesForm.roleName,
          roleDesc: this.editRolesForm.roleDesc
        })
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        this.$message.success(res.meta.msg)
        this.editRolesDialog = false
        this.getRoleList()
      })
    },

    // 删除角色方法
    async removeRolesById(id) {
      const confirmResult = await this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err)

      if (confirmResult !== 'confirm') {
        return this.$message.error('取消了删除')
      }
      const { data: res } = await this.$http.delete(`roles/${id}`)
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)
      this.$message.success(res.meta.msg)
      this.getRoleList()
    }
  }
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 8px;
}
.btborder {
  border-top: 1px solid #eee;
}
.bdborder {
  border-bottom: 1px solid #eee;
}
.vcenter {
  display: flex;
  align-items: center;
}
</style>
